package com.yingxin.yxerp.module.inform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yx.framework.user.core.IUserSupport;
import com.yingxin.yxerp.module.inform.entity.UserNotice;
import com.yingxin.yxerp.module.inform.mapper.UserNoticeMapper;
import com.yingxin.yxerp.module.inform.service.INoticeService;
import com.yingxin.yxerp.module.inform.service.IUserNoticeService;
import com.yingxin.yxerp.module.inform.vo.req.NoticeQueryVo;
import com.yingxin.yxerp.module.inform.vo.resp.NoticeRespVo;
import com.yingxin.yxerp.module.inform.vo.resp.QtyAndTimeRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 通知公告用户信息 服务实现类
 * @author matongtong
 * @since 2023-12-08
 */

@Service
public class UserNoticeServiceImpl
        extends ServiceImpl<UserNoticeMapper, UserNotice>
        implements IUserNoticeService {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IUserSupport userSupport;

    /**
     * 获取 mapper
     */
    public UserNoticeMapper mapper() {
        return baseMapper;
    }

    /**
    * 创建
    */
    @Override
    public void create(UserNotice userNotice) {
        save(userNotice);
    }

    /**
     * 批量创建
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void createList(List<UserNotice> userNotices){
        saveBatch( userNotices );
    }

    /**
     * 全部已读
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void allRead(){
        NoticeQueryVo queryVo = new NoticeQueryVo();
        List<NoticeRespVo> respVos = noticeService.listAppVo( queryVo );
        List<UserNotice> userNotices = new ArrayList<>();
        for( NoticeRespVo vo : respVos ){
            if (vo.getReadFlag().equals("0")){
                UserNotice userNotice = new UserNotice();
                userNotice.setUserId( userSupport.getUserId() );
                userNotice.setNoticeId( vo.getId() );
                userNotices.add( userNotice );
            }
        }
        if (userNotices.size() > 0){
            saveBatch( userNotices );
        }else {
            throw new BizException("没有未读信息");
        }

    }

    /**
     * 获取未读信息条数
     */
    @Override
    public QtyAndTimeRespVo getCount(String userId) {
        return baseMapper.getCount(userId);
    }

}
